package com.example;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class UserAspect {
    private static final Logger logger = Logger.getLogger(UserAspect.class);

    @Autowired
    private UserCache cache;

    @After("execution(* com.example.UserServiceImpl.*(..))")
    public void logAfter(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        logger.debug("方法名：" + methodName + "，参数：" + argsToString(args));
    }

    @Around("execution(* com.example.UserServiceImpl.addUser(..)) || execution(* com.example.UserServiceImpl.deleteUser(..))")
    public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        if (cache.getUserName() == null || !cache.getUserName().equals("admin")) {
            logger.warn("用户：" + cache.getUserName() + "，无权限执行该操作");
            return null;
        }
        return joinPoint.proceed();
    }

    private String argsToString(Object[] args) {
        if (args == null || args.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Object arg : args) {
            sb.append(arg.toString()).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }
}